package com.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/rand")
public class ImageServlet extends HttpServlet {
	static Random rand=new Random(System.currentTimeMillis());
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		resp.setContentType("image/jpeg");
		int width=130;
		int height=28;
		BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g=img.getGraphics();
		g.setColor(new Color(230,230,230));
		g.fillRect(0, 0, width, height);
		//画干扰线
		for(int i=0;i<50;i++)
		{
			g.setColor(new Color(200+rand.nextInt(50),160+rand.nextInt(50),160+rand.nextInt(50)));
			g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
		}
		StringBuilder sb=new StringBuilder();

		for(int i=0;i<5;i++)
		{
			g.setFont(new Font("微软雅黑",Font.BOLD,20+rand.nextInt(3)));
			g.setColor(new Color(150+rand.nextInt(50),90+rand.nextInt(50),90+rand.nextInt(50)));
			int ra=rand.nextInt(3);
			byte[] x=null;
			if(ra==1){

				x=new byte[]{(byte)(65+rand.nextInt(26))};
			}else if(ra==2){
				x=new byte[]{(byte)(97+rand.nextInt(26))};
			}else{
				x=new byte[]{(byte)(48+rand.nextInt(10))};
			}
			String tem=new String(x, Charset.forName("UTF-8"));
			sb.append(tem);
			g.drawString(tem, i*22+14, 16+rand.nextInt(10));
		}
		//将画的字符记入session
		req.getSession().setAttribute("randcode", sb.toString().toLowerCase());

		ServletOutputStream os=resp.getOutputStream();
		ImageIO.write(img, "jpg", os);
	}
}
